package com.hyjy.music.util

import android.text.TextUtils
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination
import java.util.*

val MUSIC_WHITE_LIST = arrayOf(".mp3", ".flac", ".aac")

/**
 * 时间格式转换
 */
fun Int.format(): String {
    var time = this
    time /= 1000
    var minute = time / 60
    val second = time % 60
    minute %= 60
    return String.format(Locale.getDefault(), "%02d:%02d", minute, second)
}

/**
 * 给color添加透明度
 *
 * @param alpha 透明度 0F～1F
 * @return 添加透明度后的颜色
 */
fun Int.getColorWithAlpha(alpha: Float): Int {
    val min = 255.coerceAtMost(0.coerceAtLeast((alpha * 255).toInt())) shl 24
    val rgb = 0x00FFFFFF and this
    return min + rgb
}

/**
 * 根据汉字获取其拼音
 *
 * @return 拼音
 */
fun String.convertToPinYin(): String {
    val format = HanyuPinyinOutputFormat()
    // 不需要音标
    format.toneType = HanyuPinyinToneType.WITHOUT_TONE
    // 设置转换出大写字母
    format.caseType = HanyuPinyinCaseType.UPPERCASE
    val charArray = this.toCharArray()
    val sb = StringBuilder()
    for (c in charArray) {
        // 如果是空格, 跳过当前循环
        if (Character.isWhitespace(c)) {
            continue
        }
        if (c.code < 127) {
            // 不可能是汉字, 直接拼接
            sb.append(c)
        } else {
            try {
                // 获取某个字符对应的拼音. 可以获取到多音字. 单 ->DAN, SHAN
                val array = PinyinHelper.toHanyuPinyinStringArray(c, format) ?: return "#"
                val first = array[0]
                if (TextUtils.isEmpty(first)) {
                    return "#"
                }
                sb.append(first)
            } catch (e: BadHanyuPinyinOutputFormatCombination) {
                e.printStackTrace()
            }
        }
    }
    return sb.toString()
}